package com.hj.tools;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

public class PropertiesUtil {
	private PropertiesUtil(){}
	
	public static String regex = ",";
	
	/**
	 * 获取properties
	 * @param in
	 * @return
	 */
	public static Properties getProperties(String path){
		InputStream in = PropertiesUtil.class.getResourceAsStream(path);
        return getProperties(in);
	}
	
	/**
	 * 获取properties
	 * @param in
	 * @return
	 */
	public static Properties getProperties(InputStream in){
		Properties props = null;
		try {
        	props = new Properties();
			props.load(in);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
        return props;
	}
	
	/**
	 * 重新添加并覆盖之前的数据
	 * @param path
	 * @param k
	 * @param v
	 * @param desc
	 */
	public static void setProperties(String path, String key, String value, String desc){
		Properties props = new Properties();
		props.setProperty(key, value);
		addProperties(path, props, desc);
	}
	
	/**
	 * 在原有的数据上添加一条
	 * @param path
	 * @param props
	 * @param desc
	 */
	public static void addProperties(String path, Properties props, String desc) {
		try {
			OutputStream fos = new FileOutputStream(path);
			props.store(fos, desc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 在原有的数据上修改指定数据
	 * @param path
	 * @param props
	 * @param desc
	 */
	public static void updateProperties(String path, Properties props, String desc) {
		addProperties(path, props, desc);
	}
	
	/**
	 * 在原有的数据上删除指定数据
	 * @param path
	 * @param props
	 * @param desc
	 */
	public static void remove(String path, Properties props, String key, String desc){
		props.remove(key);
		addProperties(path, props, desc);
	}
	
	/**
	 * 获取value多值集合
	 * @param props
	 * @param key
	 * @param cls
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> vtoList(Properties props, String key, Class<T> cls){
		String[] vs = vtoArray(props, key);
		List<T> list = new LinkedList<T>();
		for (int i = 0; i < vs.length; i++) {
			list.add((T)vs[i]);
		}
		return list;
	}
	
	/**
	 * 获取value多值集合
	 * @param props
	 * @param key
	 * @param cls
	 * @return
	 */
	public static String[] vtoArray(Properties props, String key){
		return props.getProperty(key).split(regex);
	}
}
